package com.bbzn.device.client.controller;

import com.bbzn.device.client.vo.req.AlarmHisVO;
import com.bbzn.device.client.aspect.OperationAnnotation;
import com.bbzn.device.client.constant.CrudConstant;
import com.bbzn.device.client.constant.UserConstant;
import com.bbzn.device.client.dataobject.AlarmCnEn;
import com.bbzn.device.client.dataobject.AlarmHis;
import com.bbzn.device.client.dataobject.AlarmHisEn;
import com.bbzn.device.client.dataobject.SystemParam;
import com.bbzn.device.client.dto.history.AlarmHisDTO;
import com.bbzn.device.client.exception.DefinitException;
import com.bbzn.device.client.service.*;
import com.bbzn.device.client.service.CommonService;
import com.bbzn.device.client.utils.*;
import io.swagger.annotations.Api;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.List;

/**
 * @Author: wulongbo
 * @Date : 2021/3/29 14:04
 * @Version 1.0
 */

@Api(value = "Alarm", tags = "报警历史记录")
//@CrossOrigin
@RestController
@RequestMapping("/alarm")
public class AlarmHistoryController extends BaseApiService {

    private static Logger logger = LoggerFactory.getLogger(AlarmHistoryController.class);

    @Autowired
    private CommonService commonService;

    @Autowired
    private SystemParamByCacheService systemParamByCacheService;

    @Autowired
    private AlarmHisService alarmHisService;

    @Autowired
    private AlarmHisEnService alarmHisEnService;

    @Autowired
    private AlarmCnEnService alarmCnEnService;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * 刷新查看状态
     *
     * @return
     */
    @OperationAnnotation(content = "刷新查看状态")
    @RequestMapping(value = "/refreshStatus", method = RequestMethod.POST)
    public BaseResponse refreshStatus(@RequestBody AlarmHisVO alarmHisVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);
        if (!OptionalBean.ofNullable(alarmHisVO.getId()).isPresent()) {
            systemParam = systemParamByCacheService.getValues(UserConstant.PHO_USER_ENUM, UserConstant.PHO_UN_ID_PREFIX + language);
            throw new DefinitException(systemParam.getCode(), systemParam.getMassage());
        }
        if (language.equals("EN")) {
            AlarmHisEn alarmHisEn = new AlarmHisEn();
            alarmHisEn.setId(alarmHisVO.getId());
            alarmHisEn.setLookedStatus(1);
            alarmHisEn.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            alarmHisEn.setUpdatedBy(MayiktJwtUtils.getUsername(request, secretKey));
            alarmHisEnService.updateByPrimaryKeySelective(alarmHisEn);

            AlarmCnEn alarmCnEn = new AlarmCnEn();
            alarmCnEn.setEnId(alarmHisVO.getId());
            List<AlarmCnEn> alarmCnEns = alarmCnEnService.selectSelective(alarmCnEn);

            if (CollectionUtils.isNotEmpty(alarmCnEns)) {
                AlarmCnEn needAlarmCnEn = alarmCnEns.get(0);
                if (OptionalBean.ofNullable(needAlarmCnEn).isPresent()) {
                    AlarmHis alarmHis = new AlarmHis();
                    alarmHis.setId(needAlarmCnEn.getCnId());
                    alarmHis.setLookedStatus(1);
                    alarmHis.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    alarmHis.setUpdatedBy(MayiktJwtUtils.getUsername(request, secretKey));
                    alarmHisService.updateByPrimaryKeySelective(alarmHis);
                }
            }
        } else {
            AlarmHis alarmHis = new AlarmHis();
            alarmHis.setId(alarmHisVO.getId());
            alarmHis.setLookedStatus(1);
            alarmHis.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            alarmHis.setUpdatedBy(MayiktJwtUtils.getUsername(request, secretKey));
            alarmHisService.updateByPrimaryKeySelective(alarmHis);

            AlarmCnEn alarmCnEn = new AlarmCnEn();
            alarmCnEn.setCnId(alarmHisVO.getId());
            List<AlarmCnEn> alarmCnEns = alarmCnEnService.selectSelective(alarmCnEn);
            if (CollectionUtils.isNotEmpty(alarmCnEns)) {
                AlarmCnEn needAlarmCnEn = alarmCnEns.get(0);
                if (OptionalBean.ofNullable(needAlarmCnEn).isPresent()) {
                    AlarmHisEn alarmHisEn = new AlarmHisEn();
                    alarmHisEn.setId(needAlarmCnEn.getEnId());
                    alarmHisEn.setLookedStatus(1);
                    alarmHisEn.setUpdateTime(new Timestamp(System.currentTimeMillis()));
                    alarmHisEn.setUpdatedBy(MayiktJwtUtils.getUsername(request, secretKey));
                    alarmHisEnService.updateByPrimaryKeySelective(alarmHisEn);
                }
            }
        }
        systemParam = systemParamByCacheService.getValues(CrudConstant.CRUD_ENUM, CrudConstant.MODIFY_SUCCESS_PREFIX + language);
        return setResultSuccess(systemParam.getMassage());
    }

    /**
     * 查询历史报警记录-带状态和报警类型查询
     * WEB不看自己绑定的设备
     *
     * @param alarmHisVO
     * @return
     */
    @RequestMapping(value = "/alarmHistoryByPage", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询历史报警记录-带状态查询")
    public BaseResponse alarmHistoryByPage(@RequestBody AlarmHisVO alarmHisVO, HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);

        if (null == alarmHisVO.getPageNum()) {
            alarmHisVO.setPageNum(1);
        }
        if (null == alarmHisVO.getPageSize()) {
            alarmHisVO.setPageSize(10);
        }

        AlarmHisDTO dto = new AlarmHisDTO();
        dto.setOperatorId(userId);
        dto.setUserId(userId);
        //应前端要求加上id查询 他要用
        if (OptionalBean.ofNullable(alarmHisVO.getId()).isPresent()) {
            dto.setId(alarmHisVO.getId());
        }
        if (null != alarmHisVO.getPageNum()) {
            dto.setPageNum(alarmHisVO.getPageNum());
        }
        if (null != alarmHisVO.getName()) {
            dto.setUserName(alarmHisVO.getName());
        }
        if (null != alarmHisVO.getDeviceCategoryId()) {
            dto.setDeviceCategoryId(alarmHisVO.getDeviceCategoryId());
        }
        if (null != alarmHisVO.getImei()) {
            dto.setImei(alarmHisVO.getImei());
        }
        if (null != alarmHisVO.getAlarmType()) {
            dto.setAlarmType(alarmHisVO.getAlarmType());
        }
        if (null != alarmHisVO.getDeviceType()) {
            dto.setDeviceType(alarmHisVO.getDeviceType());
        }
        if (null != alarmHisVO.getTitle()) {
            dto.setTitle(alarmHisVO.getTitle());
        }
        if (null != alarmHisVO.getCreateStartTime()) {
            dto.setCreateStartTime(alarmHisVO.getCreateStartTime());
        }
        if (null != alarmHisVO.getCreateEndTime()) {
            dto.setCreateEndTime(alarmHisVO.getCreateEndTime());
        }
        if (null != alarmHisVO.getPageSize()) {
            dto.setPageSize(alarmHisVO.getPageSize());
        }
        dto.setStartIndex((alarmHisVO.getPageNum() - 1) * alarmHisVO.getPageSize());
        if (OptionalBean.ofNullable(alarmHisVO.getLookedStatus()).isPresent()) {
            dto.setLookedStatus(alarmHisVO.getLookedStatus());
        }
        PageInfo<AlarmHisDTO> alarmHisDTOPageInfo = null;
        if (language.equals("EN")) {
            alarmHisDTOPageInfo = alarmHisEnService.alarmHistroryLimt(dto);
        } else {
            alarmHisDTOPageInfo = alarmHisService.alarmHistroryLimt(dto);
        }
        return setResultSuccess(alarmHisDTOPageInfo);
    }

    /**
     * 查询未查看的报警历史数量
     *
     * @return
     */
    @RequestMapping(value = "/getUnLookedCount", method = RequestMethod.POST)
    @OperationAnnotation(content = "查询未查看的报警历史数量")
    public BaseResponse getUnLookedCount(HttpServletRequest request) throws Exception {
        SystemParam systemParam = null;
        String secretKey = commonService.getWebSalt(request);
        String language = MayiktJwtUtils.getLanguage(request, secretKey);
        Long userId = commonService.getUserId(request);

        int count = 0;
        AlarmHisDTO dto = new AlarmHisDTO();
        dto.setUserId(userId);
        dto.setOperatorId(userId);
        dto.setLookedStatus(0);

        if (language.equals("EN")) {
            count = alarmHisEnService.alarmHisEnCount(dto);
        }else{
            count = alarmHisService.alarmHisCount(dto);
        }

        return setResultSuccess(count);
    }
}
